package com.xiaoling.robot;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.mlsdk.common.MLApplication;
import com.huawei.hms.mlsdk.common.MLException;
import com.huawei.hms.mlsdk.translate.MLTranslatorFactory;
import com.huawei.hms.mlsdk.translate.cloud.MLRemoteTranslateSetting;
import com.huawei.hms.mlsdk.translate.cloud.MLRemoteTranslator;
import com.xiaoling.robot.bean.DB;
import com.xiaoling.robot.bean.Msg;
import com.xiaoling.robot.config.TranslateConfig;
import com.xiaoling.robot.utils.ApiRequest;
import com.xiaoling.robot.utils.JSONUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChatActivity extends AppCompatActivity {
    private ListView msgListView;
    private EditText sendText;
    private String apiKey = "DAEDABHM0dbmzZCI5HO08r1nRGEAocbcaS3b5QrIunYZOitn6bladoaTqzTq1D8Ds822slCwCZmKs7WPDvXORwIaOETsFvuARZnuBQ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        // 从 SharedPreferences 恢复数据
        SharedPreferences sp = getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE);
        String json = sp.getString("db", "");
        DB db = JSONUtils.jsonToObject(json, DB.class);

        List<Msg> data = db.msgList;

        msgListView = findViewById(R.id.msg_list_view);
        ChatAdapter adapter = new ChatAdapter(ChatActivity.this, R.layout.item, data);
        msgListView.setAdapter(adapter);

        sendText =  findViewById(R.id.sendText);

        Button sendBtn = findViewById(R.id.send);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = sendText.getText().toString().trim();
                String json = sp.getString("db", "");
                DB db = JSONUtils.jsonToObject(json, DB.class);

                if(content.equals("")) {
                    Toast.makeText(ChatActivity.this, "发送内容不许为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if("clear all".equalsIgnoreCase(content)) { // 清除所有聊天记录
                    SharedPreferences.Editor editor = sp.edit();
                    data.clear();
                    db.msgList.clear();
                    adapter.notifyDataSetChanged();
                    editor.putString("db", JSONUtils.objectToJson(db));
                    editor.apply();
                    sendText.setText("");
                    Toast.makeText(ChatActivity.this, "clear finished", Toast.LENGTH_SHORT).show();
                    return;
                }

                if("translate".equalsIgnoreCase(content)) { // 进入翻译模式
                    data.add(new Msg(content, Msg.SENT));
                    adapter.notifyDataSetChanged();
                    msgListView.setSelection(data.size());
                    TranslateConfig.opened = true;
                    data.add(new Msg(TranslateConfig.sb.toString(), Msg.RECEIVED));
                    adapter.notifyDataSetChanged();
                    msgListView.setSelection(data.size());
                    sendText.setText("");
                    Toast.makeText(ChatActivity.this, "进入翻译模式", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TranslateConfig.opened) { // 进入翻译模式后，设置相关的语种翻译，并且提示用户输入要被翻译的文本。
                    String[] temp = content.split(",");
                    data.add(new Msg(content, Msg.SENT));
                    TranslateConfig.src = Integer.parseInt(temp[0]);
                    TranslateConfig.target = Integer.parseInt(temp[1]);
                    TranslateConfig.startTranslate = true;
                    TranslateConfig.opened = false;
                    data.add(new Msg("请输入要被翻译的文本。", Msg.RECEIVED));
                    adapter.notifyDataSetChanged();
                    msgListView.setSelection(data.size());
                    sendText.setText("");
                    return;
                }

                if(TranslateConfig.startTranslate) { // 开始翻译
                    TranslateConfig.sourceText = content;
                    TranslateConfig.setSourceText = false;
                    data.add(new Msg(content, Msg.SENT));
                    adapter.notifyDataSetChanged();
                    msgListView.setSelection(data.size());
                    sendText.setText("");

                    MLApplication.getInstance().setUserRegion(MLApplication.REGION_DR_CHINA); // 设置国家码
                    MLApplication.getInstance().setApiKey(apiKey); // API KEY
                    // 创建在线文本翻译器，使用自定义的参数配置创建文本翻译器。
                    MLRemoteTranslateSetting setting = new MLRemoteTranslateSetting
                            .Factory()
                            // 设置源语言的编码，使用ISO 639-1标准（中文繁体使用BCP-47标准）。此设置为可选项，如果不设置，将自动检测语种进行翻译。
                            .setSourceLangCode(TranslateConfig.getSrc())
                            // 设置目标语言的编码，使用ISO 639-1标准（中文繁体使用BCP-47标准）。
                            .setTargetLangCode(TranslateConfig.getTarget())
                            .create();
                    MLRemoteTranslator mlRemoteTranslator = MLTranslatorFactory.getInstance().getRemoteTranslator(setting);
                    // sourceText 是待翻译的文本，长度需小于5000个字符。
                    final Task<String> task = mlRemoteTranslator.asyncTranslate(TranslateConfig.sourceText);
                    task.addOnSuccessListener(new OnSuccessListener<String>() {
                        @Override
                        public void onSuccess(String text) {
                            runOnUiThread(new Runnable() { // 在主线程中更新UI
                                @Override
                                public void run() {
                                    data.add(new Msg(text, Msg.RECEIVED));
                                    adapter.notifyDataSetChanged();
                                    msgListView.setSelection(data.size());
                                    SharedPreferences.Editor editor = sp.edit();
                                    db.msgList = data;
                                    editor.putString("db", JSONUtils.objectToJson(db));
                                    editor.apply();
                                }
                            });
                            if (mlRemoteTranslator!= null) { // 翻译完成后，释放资源。
                                mlRemoteTranslator.stop();
                            }
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(Exception e) {
                            // 识别失败的处理逻辑。
                            try {
                                MLException mlException = (MLException)e;
                                // 获取错误码，开发者可以对错误码进行处理，根据错误码进行差异化的页面提示。
                                int errorCode = mlException.getErrCode();
                                System.out.println(errorCode);
                                // 获取报错信息，开发者可以结合错误码，快速定位问题。
                                String errorMessage = mlException.getMessage();
                                System.out.println(errorMessage);
                            } catch (Exception error) {
                                // 转换错误处理。
                            }
                        }
                    });
                    TranslateConfig.startTranslate = false;
                    Toast.makeText(ChatActivity.this, "翻译模式结束", Toast.LENGTH_SHORT).show();
                    return;
                }

                // ------------------------------------------------------------------------------
                // 以下是人工智能对话模式
                // ------------------------------------------------------------------------------

                data.add(new Msg(0, content, Msg.SENT));
                adapter.notifyDataSetChanged();
                msgListView.setSelection(data.size());

                String url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + content;
                ApiRequest.sendGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        // 请求失败的处理逻辑
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String json = response.body().string();
                        Msg msg = JSONUtils.jsonToObject(json, Msg.class);
                        msg.setStatus(Msg.RECEIVED);
                        runOnUiThread(new Runnable() { // 在主线程中更新UI
                            @Override
                            public void run() {
                                data.add(msg);
                                adapter.notifyDataSetChanged();
                                msgListView.setSelection(data.size());
                                SharedPreferences.Editor editor = sp.edit();
                                db.msgList = data;
                                editor.putString("db", JSONUtils.objectToJson(db));
                                editor.apply();
                            }
                        });
                    }
                });
                sendText.setText(""); // 清空输入框的内容
            }
        });
    }
}
